const initialState = {
  articles: {} as ArticleStateType,
  detail: {} as ArticleDetailType,
};

export type ArticleActionType =
  | {
      type: 'article/saveList';
      payload: {
        results: ArticleType[];
        pre_timestamp: number;
        channel_id: number;
      };
    }
  | {
      type: 'article/udpateListById';
      payload: {
        results: ArticleType[];
        pre_timestamp: number;
        channel_id: number;
      };
    }
  | {
      type: 'article/saveDetail';
      payload: ArticleDetailType;
    }
  | { type: 'article/clearDetail'; payload: {} };
export default function articleReducer(
  state = initialState,
  action: ArticleActionType
): typeof initialState {
  switch (action.type) {
    case 'article/saveList':
      const { results, pre_timestamp, channel_id } = action.payload;
      console.log(channel_id);
      return {
        ...state,
        articles: {
          ...state.articles,
          //   动态属性
          [channel_id]: {
            results,
            pre_timestamp,
          },
        },
      };
    //   case下拉刷新
    case 'article/udpateListById':
      // 要更新的数据改名
      const {
        results: update_results,
        pre_timestamp: update_timestamp,
        channel_id: update_id,
      } = action.payload;
      // 要更新的channel_id
      // 最新的时间戳
      // 新的数组
      const oldResults = state.articles[update_id]?.results || [];
      const newResults = [...oldResults, ...update_results];
      // 取出旧的result
      // 把新的reulst与旧的合并
      // 覆盖state中的旧数据
      return {
        ...state,
        articles: {
          ...state.articles,
          [update_id]: {
            results: newResults,
            pre_timestamp: update_timestamp,
            // results:newResults,
            // pre_timestamp:update_timestamp
          },
        },
      };
    case 'article/saveDetail':
      return {
        ...state,
        detail: {
          ...action.payload,
        },
      };
    case 'article/clearDetail':
      return {
        ...state,
        detail: {} as any,
      };
    default:
      return state;
  }
}
// 设计数据结构，每一个文章结构
export type ArticleType = {
  art_id: string;
  title: string;
  aut_id: string;
  comm_count: number;
  pubdate: string;
  aut_name: string;
  is_top: number;
  cover: {
    type: number;
    images: string[];
  };
};
type ArticleStateType = {
  [channels_id: number]: {
    results: ArticleType[];
    pre_timestamp: number;
  };
};

export type ArticleDetailType = {
  art_id: string;
  title: string;
  pubdate: string;
  aut_id: string;
  content: string;
  aut_name: string;
  aut_photo: string;
  is_followed: boolean;
  is_collected: boolean;
  attitude: number;
  comm_count: number;
  read_count: number;
  like_count: number;
};
